<template>
  <el-page-header class="head" :icon="null" title="云手机平台">
    <template #content>
      <div><span>登录</span></div>
    </template>
  </el-page-header>
  <div class="page-content" v-loading="loading">
    <div class="login-content">
      <div class="login-title">登录到您的云手机平台</div>
      <div class="login-form">
        <el-tabs class="tabs" type="card" v-model="loginType">
          <el-tab-pane label="WebSocket" name="websocket">
            <el-form
              ref="websocketRef"
              :rules="websocketRules"
              status-icon
              :model="websocketForm"
              label-width="0px"
              size="small"
              class="form-content"
            >
              <div
                :class="[
                  {
                    'focus-title': selectedInput === 'ip',
                  },
                  'item-title',
                ]"
              >
                IP
              </div>
              <el-form-item label="" prop="ip">
                <el-input
                  @focus="changeInputSelected('ip')"
                  v-model="websocketForm.ip"
                ></el-input>
              </el-form-item>
              <div
                :class="[
                  {
                    'focus-title': selectedInput === 'port',
                  },
                  'item-title',
                ]"
              >
                PORT
              </div>
              <el-form-item label="" prop="port">
                <el-input
                  @focus="changeInputSelected('port')"
                  v-model="websocketForm.port"
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="IAM" name="iam">
            <el-form
              :model="iamForm"
              ref="iamRef"
              :rules="iamRules"
              label-width="0px"
              size="small"
              class="form-content"
            >
              <div
                :class="[
                  {
                    'focus-title': selectedInput === 'domainId',
                  },
                  'item-title',
                ]"
              >
                租户名/原华为云账号
              </div>
              <el-form-item label="" prop="domainId">
                <el-input
                  @focus="changeInputSelected('domainId')"
                  v-model="iamForm.domainId"
                ></el-input>
              </el-form-item>
              <div
                :class="[
                  {
                    'focus-title': selectedInput === 'username',
                  },
                  'item-title',
                ]"
              >
                IAM用户名/邮件地址
              </div>
              <el-form-item label="" prop="username">
                <el-input
                  @focus="changeInputSelected('username')"
                  v-model="iamForm.username"
                ></el-input>
              </el-form-item>
              <div
                :class="[
                  {
                    'focus-title': selectedInput === 'password',
                  },
                  'item-title',
                ]"
              >
                IAM用户密码
              </div>
              <el-form-item label="" prop="password">
                <el-input
                  type="password"
                  @focus="changeInputSelected('password')"
                  v-model="iamForm.password"
                  show-password
                ></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <el-button type="primary" class="login-btn" @click="handleSubmit()">
          登录
        </el-button>
      </div>
      <div class="login-tip">
        为了获得最佳用户体验，请使用Chrome浏览器进行操作
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { iamLogin } from '@/request/request';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  data() {
    return {
      trustHtml: '',
      loading: false,
      loginType: 'websocket',
      selectedInput: '',
      websocketForm: {
        ip: '',
        port: '',
      },
      iamForm: {
        domainId: '',
        username: '',
        password: '',
      },
      websocketRules: {
        ip: [
          {
            required: true,
            min: 1,
            max: 32,
            message: '请检查IP',
            trigger: ['blur', 'change'],
          },
        ],
        port: [
          {
            required: true,
            min: 1,
            max: 32,
            message: '请检查端口号',
            trigger: ['blur', 'change'],
          },
        ],
      },
      iamRules: {
        domainId: [
          {
            required: true,
            min: 1,
            max: 32,
            message: '请检查租户名',
            trigger: ['blur', 'change'],
          },
        ],
        username: [
          {
            required: true,
            min: 1,
            max: 32,
            message: '请检查用户名',
            trigger: ['blur', 'change'],
          },
        ],
        password: [
          {
            required: true,
            min: 1,
            max: 32,
            message: '请检查密码',
            trigger: ['blur', 'change'],
          },
        ],
      },
    };
  },
  methods: {
    async handleSubmit() {
      if (this.loginType === 'websocket') {
        await this.$refs.websocketRef.validate((valid: any) => {
          if (valid) {
            this.setSingleStorage();
          }
        });
      }

      if (this.loginType === 'iam') {
        await this.$refs.iamRef.validate((valid: any) => {
          if (valid) {
            this.iamLogin();
          }
        });
      }
    },

    async iamLogin() {
      try {
        this.loading = true;
        if (!localStorage.getItem('region')) {
          localStorage.setItem('region', 'cn-southwest-2');
        }
        const res: any = await iamLogin(this.iamForm);
        const region = localStorage.getItem('region');
        localStorage.setItem('token', res.headers['x-subject-token']);
        localStorage.setItem(
          'project_id',
          JSON.stringify({
            [region]: res.data.token.project.id,
          }),
        );
        localStorage.setItem(
          'user_info',
          JSON.stringify({
            domainId: this.iamForm.domainId,
            username: this.iamForm.username,
            password: this.iamForm.password,
          }),
        );
        this.$router.push('/phoneList');
      } catch (e) {
        if (e.response.data.error.message) {
          ElMessage.error(e.response.data.error.message);
        }
        console.log(e);
      } finally {
        this.loading = false;
      }
    },

    setSingleStorage() {
      const phoneHost = {
        ip: this.websocketForm.ip,
        port: this.websocketForm.port,
      };
      sessionStorage.setItem('cloudPhoneHost', JSON.stringify(phoneHost));
      sessionStorage.setItem('channelType', 'WebSocket');
      const targetStr = [phoneHost.ip, phoneHost.port].join(':');
      const trustTargetStr = sessionStorage.getItem('trustTargetList');
      if (trustTargetStr && JSON.parse(trustTargetStr).includes(targetStr)) {
        this.$router.push('/singlePHone');
      } else {
        this.trustHtml = 'https://' + [phoneHost.ip, phoneHost.port].join(':');
        ElMessageBox.alert(
          `<iframe style="width: 650px; height: 550px;" src="${this.trustHtml}" frameborder="0"></iframe>`,
          '首次接入需等待此页面的加载以进行信任',
          {
            customStyle: {
              maxWidth: '720px',
              maxHeight: '680px',
              padding: '20px',
            },
            center: true,
            showClose: false,
            confirmButtonText: '已信任',
            dangerouslyUseHTMLString: true,
            callback: () => {
              this.$router.push('/singlePHone');
            },
          },
        );
      }
    },

    changeInputSelected(type: string) {
      this.selectedInput = type;
    },
  },
};
</script>

<style scoped lang="less">
.login-content {
  height: 100vh;
  background-color: #f5f6f8;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 10vh;
}

.login-form {
  padding: 40px 20px;
  background-color: #fff;
  border: 2px solid #dbdbdb;
  border-radius: 10px;
  box-shadow: 5px 5px 10px #d9d9d9;
}

.login-title {
  font-size: 24px;
  margin-bottom: 30px;
}

.form-content {
  padding: 20px;
}

.login-btn {
  width: 80%;
  height: 50px;
  margin-left: 10%;
}

.alert {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
}

.login-tip {
  color: #999;
  margin-top: 10px;
  font-size: 12px;
}

.item-title {
  margin-bottom: 10px;
  margin-top: 20px;
  font-size: 12px;
}

.focus-title {
  color: #1476ff;
}

.trust-msg {
  margin: 0px;
  text-align: left;
  font-size: 14px;
  text-indent: 2em;
}

@media screen and (min-width: 720px) {
  .head {
    padding: 20px;
    :deep(.el-page-header__title) {
      color: var(--el-text-color-primary);
      font-size: 18px;
    }
  }

  .login-form {
    width: 500px;
  }
}

@media screen and (max-width: 720px) {
  .head {
    display: none;
  }
  .login-form {
    width: calc(100vw - 20px);
  }
}
</style>
